package no.sogl.domain;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.EntityManager;
import javax.persistence.ManyToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;

import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.tostring.RooToString;
import org.springframework.transaction.annotation.Transactional;

@RooJavaBean
@RooToString
@RooJpaActiveRecord
public class TeamMember {
    @ManyToOne
    private Person member;

    @ManyToOne
    private Team team;

    @NotNull
    private boolean active = true;

    @NotNull
    @Temporal(TemporalType.TIMESTAMP)
    @DateTimeFormat(style = "S-")
    @Column(updatable = false, insertable = true)
    private Date createdAt = new Date();

    @NotNull
    @Temporal(TemporalType.TIMESTAMP)
    @DateTimeFormat(style = "S-")
    private Date joinedOn = new Date();

    @NotNull
    @Temporal(TemporalType.TIMESTAMP)
    @DateTimeFormat(style = "SS")
    private Date updatedAt = new Date();

    public TeamMember() {
        super();
    }

    public TeamMember(Person member, Team team) {
        this();
        this.member = member;
        this.team = team;
    }

    @Transactional
    public void persist() {
        if (active) member.addTag(team.getName());
        TeamMember.entityManager().persist(this);
    }

    @Transactional
    public TeamMember merge() {
        updatedAt = new Date();
        if (active) member.addTag(team.getName());
        else member.removeTag(team.getName());
        TeamMember merged = TeamMember.entityManager().merge(this);
        this.entityManager.flush();
        return merged;
    }

    @Transactional
    public void remove() {
        member.removeTag(team.getName());
        EntityManager em = TeamMember.entityManager();
        if (em.contains(this)) {
            em.remove(this);
        } else {
            TeamMember attached = TeamMember.findTeamMember(getId());
            em.remove(attached);
        }
    }

}
